package edu.ynu.se.xiecheng.achitectureclass.controller;

import edu.ynu.se.xiecheng.achitectureclass.service.IDeviceDataService;
import edu.ynu.se.xiecheng.achitectureclass.dto.DeviceDataWithGreenhouseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;

import java.util.List;

@RestController
@RequestMapping("/api/sensors")
@CrossOrigin(origins = "http://localhost:5173", allowedHeaders = "*", allowCredentials = "true")
public class DeviceDataController {
    @Autowired
    private IDeviceDataService sensorDataService;

    @GetMapping
    public ResponseEntity<List<DeviceDataWithGreenhouseDTO>> getAllSensors(@RequestParam Long greenhouseId) {
        return ResponseEntity.ok(sensorDataService.getAllSensorsData(greenhouseId));
    }

    @PostMapping("/refresh")
    public ResponseEntity<Boolean> refreshData(
            @RequestParam Long greenhouseId,
            @RequestHeader("Authorization") String token) {
        // 验证token
        if (!token.equals("Bearer " + "eyJhbGciOiJSUzI1NiIsImtpZCI6Ijg2QzQ2RTIxQTc0MTUxNTFCOTQ0MTY4MzhEMERGODU1OTZENkM2RTgiLCJ0eXAiOiJhdCtqd3QiLCJ4NXQiOiJoc1J1SWFkQlVWRzVSQmFEalEzNFZaYld4dWcifQ.eyJuYmYiOjE3MzYzNzIzMzQsImV4cCI6MTczNjM3OTUzNCwiaXNzIjoiaHR0cHM6Ly9hY2NvdW50LmZsZXhlbS5jb20vY29yZSIsImF1ZCI6Imlkc3ZyMyIsImNsaWVudF9pZCI6IjY4ZGIyZThiZGE4ZDQ3YjViNWRiN2VhZjcxYzdkY2RkIiwic3ViIjoiZTcxMjRhMTYtMjEwNS00ZTU4LWI5OGItOWE2ZmFkNjZiYjA3Iiwic2NvcGUiOlsiZmJveCJdfQ.QFhASPp19K6oFLM1MqhKsemtRLiu_8AZGTCmCn6fGvbPg9GIxJGuGekThrgimAOKPQYoCNfFqlXQFDlm5COU-jBdshm3GscJuiQQ0wjrzjy7edMENhc2D87PWUag7TJ_isZ479O7yec24X1gGX-FwYjiQU1ToNiM0Tl4ndWa21EpFfiXXB4jfpCgwC-BxqZdi2E4vgtqrdoVAU9ACvVBJl-w8Jr1Q7qQtrRPDChMaajq3mGGp10wgFCg_hcrKi0Brg5NWZKInR5dRxdczEDeTsEUJBhZC_0i5Q94lgBQNtjHMKoe0kNA2pB41NVtsHv5EUOGsV8dQE5xpmqL6YQevA")) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(false);
        }
        return ResponseEntity.ok(sensorDataService.refreshData(greenhouseId));
    }
}
